<script setup>
import { reactive, ref } from 'vue'
import { resetUserPassword } from '@/api/system'
import { getCaptchaByPhoneNo, resetPassword } from '@/api/system'

const registerForm = ref()

const resetParams = reactive({
  telephone: null,
  oldPassword: null,
  newPassword: null,
  Captcha: null
})

const text = ref("获取验证码")

const customRules = reactive({
  telephone: {
    rules: [
      { required: true, errorMessage: '手机号不能为空' },
      { validator: validatePhone },
    ]
  },
  oldPassword: {
    rules: [
      { required: true, errorMessage: '请输入要修改的密码' },
      { validator: validatePwd },
    ]
  },
  newPassword: {
    rules: [{ required: true, errorMessage: '请再次输入密码进行确认' }]
  },
  Captcha: {
    rules: [{ required: true, errorMessage: '验证码不能为空' }]
  }
})

function validatePhone(rule, value, callback) {
  if (value === "") {
    callback(new Error("请输入手机号"));
  } else {
    if (!/^1[3456789]\d{9}$/.test(value)) {
      callback(new Error("请输入正确的手机号"));
    } else {
      callback();
    }
  }
}

function validatePwd(rule, value, callback) {
  if (value === "") {
    callback(new Error("请输入密码"));
  } else {
    let reg = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\\W_!@#$%^&*`~()-+=]+$)(?![0-9\\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\\W_!@#$%^&*`~()-+=]{9,20}$/;
    if (!reg.test(value)) {
      callback(
        new Error(
          "请输入正确的密码，必须包含大小写字母、数字、特殊字符中的三种"
        )
      );
    } else {
      callback();
    }
  }
}

/**
 * 获取验证码
 */
const getCaptcha =async () => {
  if(resetParams.telephone){
      // 开始倒计时
      let timeCount = 60

      text.value = timeCount + '秒后重新获取'

      const timer = setInterval(() => {
        if (timeCount === 0) {
          clearInterval(timer);
          text.value = "获取验证码";
        } else {
          timeCount--;
          text.value = timeCount + "秒后重新获取";
        }
      }, 1000);

      const result=await getCaptchaByPhoneNo(resetParams.telephone)
      console.log(22222222222222, result)
      const {code, msg} = result;
      if (code == 200) {
        console.log(3333333, code, msg)
        uni.showToast({
          title: '短信发送成功',
          icon: 'none',
          duration: 2000,
          mask: false
        });
        // return
      } else {
        console.log(44444444, code, msg)
        uni.showModal({ title: '提示', content: msg })
      }
  }
}
/**
 * 倒计时
 */
 const startCountdown = () => {

}

/**
 * 重置密码
 */
const handleResetPassword = async () => {
  registerForm.value
    .validate()
    .then(async ({ oldPassword, newPassword }) => {
      if (oldPassword !== newPassword) {
        return uni.showModal({ title: '提示', content: '两次输入的密码不同，请重新输入！' })
      }

      // else {
      //   uni.showModal({ title: '提示', content: '修改成功' })
      //   uni.reLaunch({
      //     url: '/pages/login/index'
      //   })
      // }
      const { code, msg } = await resetPassword({
        phone: resetParams.telephone,
        captcha: resetParams.Captcha,
        password: resetParams.oldPassword,
        repeatPassword: resetParams.newPassword,
      })
      if (code == 200) {
        uni.showModal({
          title: '提示',
          content: msg,
          showCancel: false,
          success: (res) => {
            if (res.confirm) {
              uni.removeStorageSync('accessToken')
              uni.reLaunch({
                url: '/pages/login/index'
              })
            }
          }
        })
        return
      }

      uni.showModal({ title: '提示', content: msg })
    })
    .catch((err) => {
      console.log('err', err)
    })
}
</script>
<template>
  <view class="example">
    <uni-forms
      label-position="left"
      label-width="80"
      :modelValue="resetParams"
      :rules="customRules"
      ref="registerForm"
      class="form"
    >
      <uni-forms-item label="手机号码" required name="telephone">
        <uni-easyinput 
          placeholder="请输入手机号" 
          v-model="resetParams.telephone" 
        />
      </uni-forms-item>
      <uni-forms-item label="输入密码" required name="oldPassword">
        <uni-easyinput 
          placeholder="请输入要修改的密码" 
          v-model="resetParams.oldPassword" 
          type="password"
        />
      </uni-forms-item>
      <uni-forms-item label="确认密码" required name="newPassword">
        <uni-easyinput 
          placeholder="请再次确认密码" 
          v-model="resetParams.newPassword"
          type="password"
        />
      </uni-forms-item>
      <uni-forms-item label="验证码：" required name="Captcha">
        <view style="display: flex; align-items: center">
            <uni-easyinput
              placeholder="请输入验证码"
              style="display: inline-block; width: 60%;"
              v-model="resetParams.Captcha"
            />
            <button type="primary" @click="getCaptcha" class="captchaBtn" 
            :disabled="!resetParams.telephone || text == '获取验证码' ? false : true"
            >{{ text }}</button>
          </view>
      </uni-forms-item>
    </uni-forms>
    <button type="primary" @click="handleResetPassword">修改密码</button>
  </view>
</template>

<style lang="scss" scoped>
.form {
  margin-bottom: 22px;
}
.example {
  padding: 15px;
  background-color: #fff;
}
.captchaBtn {
  line-height: 35px;
  font-size: 14px;
  height: 35px;
  margin-left: 8px;
}

button[disabled] {
    color: #fff !important;
    background: #71b2f9 !important;
    border-color: #28aed7 !important;
}
</style>
